<template>
    <el-card shadow="never">
        <store-progress v-model="step" :type="2" />
    </el-card>
    <el-card shadow="never" style="margin: 16px 0">
        <div class="content">
            <div class="storeTips">
                <store-tips :type="3" />
            </div>
            <div class="line"></div>
            <div v-if="step === 1" class="msg">
                <el-form
                    ref="stepOneDataRef"
                    :model="stepOneData"
                    :rules="stepOneDataRules"
                    label-width="auto"
                    :disabled="pageType == 'look'">
                    <div class="title">服务应用</div>
                    <el-form-item label="服务应用：" prop="service_application">
                        <el-radio-group v-model="stepOneData.service_application">
                            <el-radio :label="1"> 应用服务 </el-radio>
                            <el-radio :label="2"> 暂不购买 </el-radio>
                        </el-radio-group>
                        <div v-if="stepOneData.service_application == 1" class="formTips">
                            <span>
                                选择应用该服务，同意签署
                                <span class="toAgreement" @click="toAgreement">《客易达数据安全隐私协议》</span>
                                文件。客易达将自动同步来自天猫/淘宝店铺的订单、商品、用户数据。
                            </span>
                        </div>
                        <div v-if="stepOneData.service_application == 2" class="formTips">
                            选择暂不购买，无需店铺授权。可通过天猫/淘宝店铺后台下载订单、商品数据、导入系统。
                        </div>
                    </el-form-item>

                    <el-form-item v-if="stepOneData.service_application == 1" label="线路：" prop="sync_line">
                        <el-select v-model="stepOneData.sync_line" :disabled="shopInfo.shop_id">
                            <el-option
                                v-for="item in lineList"
                                :key="item.app_id"
                                :label="item.app_line_alias"
                                :value="item.app_id"
                                :disabled="item.is_disable == 1">
                            </el-option>
                        </el-select>
                        <span class="customerTips">
                            请先联系
                            <span class="customerService" @click="changePackage = true">客服</span>
                            ，开通线路后使用！
                        </span>
                    </el-form-item>

                    <div class="title">店铺基本信息</div>
                    <el-form-item v-if="type == 'edit' || type == 'look'" label="客易达店铺ID：" required>
                        <div class="withTips">
                            <el-input v-model.trim="shopInfo.retail_shop_id" :disabled="type == 'edit'" />
                        </div>
                    </el-form-item>
                    <!-- RPA 需求店铺ID 字段改为应用服务、暂不购买时都显示 -->
                    <el-form-item label="店铺ID：" prop="shop_ser_number">
                        <div class="withTips">
                            <el-input
                                v-model.trim="stepOneData.shop_ser_number"
                                placeholder="请输入店铺ID"
                                :disabled="type == 'edit'"
                                @change="onChangeShopSerNumber" />
                            <span class="tip-url" @click="toCheck()"> 如何查找店铺ID？</span>
                        </div>
                    </el-form-item>
                    <el-form-item label="淘宝账号名：" prop="external_shop_id">
                        <div class="withTips">
                            <el-input
                                v-model.trim="stepOneData.external_shop_id"
                                :disabled="exterDom"
                                placeholder="请输入淘宝账号名"
                                @input="changeValue('shop_id')" />
                            <span class="tip-url" @click="toCheck()">如何查找淘宝账号名？</span>
                        </div>
                    </el-form-item>

                    <el-form-item label="店铺名称：" prop="name">
                        <div class="withTips">
                            <el-input v-model.trim="stepOneData.name" placeholder="请输入店铺名称" />
                            <span class="tip-url" @click="toCheck()">如何查找店铺名称？</span>
                        </div>
                    </el-form-item>
                    <el-form-item label="店铺LOGO：" prop="logo">
                        <store-upload v-model="stepOneData.logo" />
                    </el-form-item>

                    <el-form-item
                        v-if="
                            stepOneData.service_application == 1 && stepOneData.sync_line !== SyncLine['RPA_SYNC_LINE']
                        "
                        label="店铺首页："
                        prop="external_shop_index_url">
                        <div class="withTips">
                            <el-input
                                v-model.trim="stepOneData.external_shop_index_url"
                                placeholder="请输入店铺首页地址"
                                @input="changeValue" />
                            <span class="tip-url" @click="changePackage = true">联系客服获取</span>
                        </div>
                    </el-form-item>

                    <el-form-item
                        v-if="
                            stepOneData.service_application == 1 && stepOneData.sync_line !== SyncLine['RPA_SYNC_LINE']
                        "
                        label="授权码："
                        prop="shop_auth_code">
                        <div class="withTips">
                            <el-input
                                v-model.trim="stepOneData.shop_auth_code"
                                placeholder="请输入授权码"
                                @input="changeValue">
                                <template #append>
                                    <span class="verify-btn" @click="toverifyCode">
                                        {{ checkCode.isCheck ? '重新校验' : '校验' }}
                                        <el-icon v-if="isShowLoading1" class="rotate-loading">
                                            <Loading />
                                        </el-icon>
                                    </span>
                                </template>
                            </el-input>
                            <span class="tip-url" @click="changePackage = true">联系客服获取</span>
                        </div>
                        <div>
                            <span v-if="checkCode.status == 1" class="verify-pass-text">校验通过</span>
                            <span v-if="checkCode.status == 2" class="verify-fail-text">
                                该授权码校验失败，请先联系
                                <span class="customer" @click="changePackage = true">客服</span> 协助！
                            </span>
                        </div>
                    </el-form-item>

                    <template v-if="stepOneData.service_application == 1">
                        <div class="title">数据配置</div>
                        <el-form-item v-if="stepOneData.sync_line !== SyncLine['RPA_SYNC_LINE']" label="数据同步：">
                            <el-switch
                                v-model="stepOneData.is_timing_sync_order"
                                :active-value="1"
                                :inactive-value="2"
                                style="--el-switch-on-color: #ff6b00; --el-switch-off-color: #dcdfe6" />
                            <span class="customerTips">开启后，天猫订单、商品相关数据将会同步至SCRM</span>
                        </el-form-item>

                        <el-form-item
                            v-if="stepOneData.is_timing_sync_order == 1"
                            label="同步周期："
                            prop="order_sync_time">
                            <div class="syncTime">
                                <span class="margin-l">每日 </span>
                                <el-time-picker
                                    v-model="stepOneData.order_sync_time"
                                    format="HH:mm"
                                    value-format="HH:mm"
                                    placeholder="请选择同步时间" />
                            </div>
                        </el-form-item>

                        <el-form-item label="虚拟号服务：">
                            <el-switch
                                v-model="stepOneData.is_open_virtual"
                                :active-value="1"
                                :inactive-value="2"
                                style="--el-switch-on-color: #ff6b00; --el-switch-off-color: #dcdfe6" />
                            <span class="customerTips">
                                开启后，客易达将为您提供未解析订单（包括解析后为虚拟号的订单）的客户匹配服务
                            </span>
                            <div v-if="stepOneData.is_open_virtual == 1" class="virtualNumber">
                                <span class="customerTips customer-sever">
                                    请先联系
                                    <span class="customerService" @click="changePackage = true"> 客服 </span>
                                    ，配置成功后使用！
                                </span>
                                <el-form-item label="店铺ID：" prop="shop_id">
                                    <div class="withTips">
                                        <el-input
                                            v-model.trim="stepOneData.shop_id"
                                            :disabled="isDisabledDom"
                                            placeholder="请输入店铺ID"
                                            @change="onChangeShopId">
                                            <template #append>
                                                <span class="verify-btn" @click="toverifyNum">
                                                    {{ checkShopId.isCheck ? '重新校验' : '校验' }}
                                                    <el-icon v-if="isShowLoading2" class="rotate-loading">
                                                        <Loading />
                                                    </el-icon>
                                                </span>
                                            </template>
                                        </el-input>
                                        <span class="tip-url" @click="toCheck()">如何查找店铺ID？</span>
                                    </div>
                                    <div>
                                        <span v-if="checkShopId.status == 1" class="verify-pass-text">校验通过</span>
                                        <span v-else class="verify-fail-text">
                                            {{ showDom }}
                                            <template v-if="[2, 3].includes(checkShopId.status)">
                                                <span class="customer" @click="changePackage = true">客服</span>
                                                {{ checkShopId.status == 2 ? ' 购买！' : '协助！' }}
                                            </template>
                                        </span>
                                    </div>
                                </el-form-item>
                            </div>
                        </el-form-item>
                    </template>
                    <!-- 推广活动 of start -->
                    <template v-if="stepOneData.service_application == 1">
                        <div class="title">推广活动</div>
                        <el-form-item label="服务开启：" prop="is_open_promotion">
                            <el-switch
                                v-model="stepOneData.is_open_promotion"
                                :active-value="2"
                                :inactive-value="1"
                                style="--el-switch-on-color: #ff6b00; --el-switch-off-color: #dcdfe6" />
                            <span class="customerTips"
                                >推广活动开通后，商家即可通过商品活动的分享，追踪淘宝商品的用户行为及交易数据的回流情况。</span
                            >
                            <div
                                v-if="stepOneData.service_application == 1 && stepOneData.is_open_promotion == 2"
                                class="formTips"
                                style="display: flex; flex-direction: row">
                                请先联系<span class="customerService" @click="changePackage = true">客服</span
                                >，获取授权码，配置开通后生效。
                            </div>
                        </el-form-item>
                        <el-form-item
                            v-if="stepOneData.is_open_promotion == 2"
                            label="店铺ID："
                            prop="shop_ser_number1">
                            <div class="withTips">
                                <el-input
                                    v-model.trim="stepOneData.shop_ser_number"
                                    :disabled="true"
                                    placeholder="请输入店铺ID">
                                    <template #append>
                                        <span
                                            class="verify-btn"
                                            :style="{
                                                cursor: ['look'].includes(type) ? 'not-allowed' : 'pointer'
                                            }"
                                            @click="toverifyShopSerNumber">
                                            {{ checkShopSerNumber.isCheck ? '重新校验' : '校验' }}
                                            <el-icon v-if="isShowLoading3" class="rotate-loading">
                                                <Loading />
                                            </el-icon>
                                        </span>
                                    </template>
                                </el-input>
                            </div>
                            <div>
                                <span v-if="checkShopSerNumber.status == 2" class="verify-pass-text">校验成功</span>
                                <span v-if="checkShopSerNumber.status == 1" class="verify-fail-text">
                                    该店铺验证失败，请先联系
                                    <template v-if="[1].includes(checkShopSerNumber.status)">
                                        <span class="customer" @click="changePackage = true">客服</span>
                                    </template>
                                    协助！
                                </span>
                            </div>
                        </el-form-item>
                        <el-form-item
                            v-if="stepOneData.is_open_promotion == 2"
                            label="活动类型："
                            prop="promotion_type">
                            <el-checkbox-group v-model="stepOneData.promotion_type">
                                <el-checkbox
                                    v-for="item in PROMOTION_ACTIVITY_TYPE"
                                    :key="item.id"
                                    :label="item.id"
                                    :name="item.id"
                                    :disabled="item.isDisabled">
                                    {{ item.name }}
                                </el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </template>
                    <!-- 推广活动 of end -->
                </el-form>
            </div>
            <div v-if="step === 2" class="finishBox">
                <el-icon :style="{ fontSize: '60px' }" color="#60B900">
                    <CircleCheckFilled />
                </el-icon>
                <div v-if="type != 'look'">{{ routers.query.shop_id ? '店铺编辑成功' : '店铺创建成功' }}</div>
                <!-- RPA需求更改为用 retail_shop_id 展示用 -->
                <div class="tag">
                    您的客易达店铺ID为：{{ shopInfo.retail_shop_id || '--' }}
                    <span v-if="shopInfo.retail_shop_id" class="tip-url" @click="copy(shopInfo.retail_shop_id)"
                        >复制</span
                    >
                </div>
                <div v-if="stepTwoData.open_platform == 1" class="tag">
                    请前往设置与开发去开启开发者功能 <span @click="toSetting">去配置</span>
                </div>
                <div v-if="initBut(0)">
                    <el-button type="primary" size="small" @click="initData">数据初始化</el-button>
                </div>
                <div v-if="initBut(2)" class="init-data">
                    <el-button type="primary" size="small" disabled>数据初始化中...</el-button>
                    <div class="time-tips">{{ stepTwoData.created_at || '--' }} 开始初始化</div>
                </div>
                <div v-if="initBut(3)" class="init-data">
                    <el-button type="primary" size="small" disabled>初始化已完成</el-button>
                    <div class="time-color">已于{{ stepTwoData.finish_time || '--' }} 完成初始化</div>
                </div>
                <div v-if="initBut(4)" class="init-data">
                    <el-button type="primary" size="small" @click="initData">重新初始化</el-button>
                    <div class="time-warning">{{ stepTwoData.finish_time || '--' }} 发起的初始化存在异常</div>
                </div>
                <div v-if="initBut(5)" class="init-data">
                    <el-button type="primary" size="small" @click="initData">重新初始化</el-button>
                    <div class="time-warning">{{ stepTwoData.finish_time || '--' }} 发起的初始化已取消</div>
                </div>
                <div class="tag">
                    <el-link :underline="false" class="tip-url link-indent" @click="changePackage = true"
                        >联系客服</el-link
                    >
                </div>
            </div>
        </div>
    </el-card>
    <div class="footer_button">
        <el-button v-if="step === 1" type="primary" @click="nextStep">下一步</el-button>
        <el-button v-if="step === 2" type="primary" @click="done">完成</el-button>
    </div>

    <el-dialog v-model="changePackage" title="企业专属顾问" width="25%" align-center>
        <div class="qwQrCode" style="text-align: center">
            <img src="https://static.scrm.keyid.cn/assets/images/global/service.png" alt="" />
        </div>
        <p style="text-align: center">扫码添加企微顾问，开通使用！</p>
    </el-dialog>
    <!--切换服务应用提醒弹窗-->
    <ZWDeletdialog ref="serviceDialogRef" @submit="onServiceDialog" />
</template>
<script lang="ts" setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import router from '@/router';
import { useRoute } from 'vue-router';
import lodash from 'lodash';
import {
    addStore,
    getStoreDetail,
    editStore,
    shopLineList,
    verifyAuthCode,
    verifyNumServe,
    shopDateInit,
    verifyShopSerNumber
} from '@/api/ecommerce/storeManage';
import storeProgress from '../components/storeProgress.vue';
import storeTips from '../components/storeTips.vue';
import storeUpload from '../components/storeUpload.vue';
import useClipboard from 'vue-clipboard3';
import ZWDeletdialog from '@/components/ZWDeletdialog.vue';
import { ShowTaskMessage } from '@/hooks/TaskMessageHooks';
import { parabolaAnimation } from '@/utils/parabola';
import { SyncLine, PROMOTION_ACTIVITY_TYPE } from '@/const/ecommerce';

const routers = useRoute();
const { channel, retail_shop_id, type } = routers.query;
const { toClipboard } = useClipboard();

const serviceDialogRef = ref();
const stepOneDataRef = ref();
const step = ref(1); // 步骤数
const changePackage = ref(false);
const isShowLoading1 = ref(false);
const isShowLoading2 = ref(false);
const isShowLoading3 = ref(false);
const lineList = ref([]);

const shopInfo = reactive<any>({
    source: null,
    shop_id: null,
    // RPA 需求增加 retail_shop_id
    retail_shop_id: null
});

const checkCode = reactive({
    isCheck: false, // 是否已校验
    status: 0, // 校验状态，0-初始值，1-通过，2-失败
    isShow: false // 是否展示请先校验
});
const checkShopId = reactive({
    isCheck: false, // 是否已校验
    status: 0, // 校验状态，0-初始值，1-通过，2-该店铺还未购买服务，3-该店铺还未授权登录，4-该店铺已授权其他店铺
    isShow: false // 是否展示请先校验
});

// 校验推广活动店铺ID
const checkShopSerNumber = reactive({
    isCheck: false, // 是否已校验
    status: 0, // 校验状态，0-初始值，1-未开通套餐 2-开通套餐
    isShow: false // 是否展示请先校验
});

const stepOneData = reactive({
    service_application: 1, // 服务应用
    sync_line: SyncLine['DEFAULT_RPA_SYNC_LINE'], // RPA需求默认线路改为线路4
    external_shop_id: '', // 淘宝账号名
    shop_ser_number: '', // 店铺ID
    name: '', // 店铺名称
    logo: '', // 店铺LOGO
    external_shop_index_url: '', // 店铺首页
    shop_auth_code: '', // 授权码
    is_timing_sync_order: 2, // 是否开启数据同步， 1-开，2-关
    order_sync_time: '23:00', // 同步周期
    is_open_virtual: 2, // 是否开启虚拟号服务，1-开，2-关
    shop_id: '', // 虚拟号店铺ID
    is_open_promotion: 1, // 推广活动服务开启，1-关，2-开
    promotion_type: [1] // 推广活动类型
});

let stepTwoData = reactive<any>({
    task_state: 0, // 异步任务状态，0-未初始化，1-未开始，2-进行中，3-已完成，4-异常（执行失败），5-已取消，6-已失效
    // async_task_id: null, // 异步任务状态id，0-未初始化，>0-已初始化
    created_at: null, // 异步任何创建时间
    finish_time: null, // 异步任务完成时间
    open_platform: null // 是否需要去配置开发项，0-否，1-是
});

let oldShopDetailInfo = reactive<any>({});

// 自定义校验店铺首页--超链接
const validateHttp = (rule: any, value: any, callback: any) => {
    if (stepOneData.service_application == 1) {
        if (value) {
            const reg = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
            if (reg.test(value) && (value.substr(0, 7) == 'http://' || value.substr(0, 8) == 'https://')) {
                callback();
            } else {
                callback(new Error('请输入带有http或https的正确URL'));
            }
        } else {
            callback(new Error('请输入店铺首页地址'));
        }
    } else {
        callback();
    }
};

// 自定义校验授权码
const validateCode = (rule: any, value: any, callback: any) => {
    if (stepOneData.service_application == 1) {
        if (!value) {
            callback(new Error('请输入授权码'));
        } else if (checkCode.isShow) {
            callback(new Error('请先校验授权码'));
        } else {
            callback();
        }
    }
};

// 自定义校验店铺ID
const validateShopId = (rule: any, value: any, callback: any) => {
    if (stepOneData.service_application == 1) {
        if (!value) {
            callback(new Error('请输入店铺ID'));
        } else if (checkShopId.isShow) {
            callback(new Error('请先校验店铺ID'));
        } else {
            callback();
        }
    }
};

/**
 * 自定义校验推广活动店铺ID
 */
const validateShopSerNumber = (rule: any, value: any, callback: any) => {
    if (stepOneData.service_application == 1) {
        if (!stepOneData.shop_ser_number) {
            callback(new Error('请输入店铺ID'));
        } else if (checkShopSerNumber.isShow) {
            callback(new Error('请先校验店铺ID'));
        } else {
            callback();
        }
    }
};

// 必填项校验规则配置
const stepOneDataRules = reactive({
    service_application: [{ required: true, message: '请选择服务应用', trigger: 'change' }],
    sync_line: [{ required: true, message: '请选择线路', trigger: 'change' }],
    external_shop_id: [{ required: true, message: '请输入淘宝账号名', trigger: 'change' }],
    shop_ser_number: [{ required: true, message: '请输入店铺ID', trigger: 'change' }],
    name: [{ required: true, message: '请输入店铺名称', trigger: 'change' }],
    logo: [{ required: true, message: '请选择店铺LOGO', trigger: 'change' }],
    external_shop_index_url: [{ required: true, validator: validateHttp, trigger: 'change' }],
    shop_auth_code: [{ required: true, validator: validateCode, trigger: 'change' }],
    order_sync_time: [{ required: true, message: '请选择同步时间', trigger: 'change' }],
    shop_id: [{ required: true, validator: validateShopId, trigger: 'change' }],
    shop_ser_number1: [{ required: true, validator: validateShopSerNumber, trigger: 'change' }],
    is_open_promotion: [{ required: true, message: '', trigger: 'change' }],
    promotion_type: [{ required: true, message: '请选择推广活动类型', trigger: 'change' }]
});

// 校验授权码
const toverifyCode = () => {
    const { external_shop_id, external_shop_index_url, shop_auth_code } = stepOneData;

    if (!external_shop_id) {
        ElMessage.warning('请先输入淘宝账号名！');
    } else if (!external_shop_index_url) {
        ElMessage.warning('请先输入店铺首页！');
    } else if (!shop_auth_code) {
        ElMessage.warning('请先输入授权码！');
    } else {
        isShowLoading1.value = true;

        const params = {
            external_shop_id,
            external_shop_index_url,
            auth_code: shop_auth_code
        };
        verifyAuthCode(params).then((res: any) => {
            checkCode.isCheck = true;
            checkCode.status = res.status;
            isShowLoading1.value = false;
            checkCode.isShow = false;
            stepOneDataRef.value.clearValidate('shop_auth_code');
        });
    }
};

// 校验虚拟号店铺ID
const toverifyNum = () => {
    if (!stepOneData.external_shop_id) {
        ElMessage.warning('请先输入淘宝账号名！');
    } else if (!stepOneData.shop_id) {
        ElMessage.warning('请输入店铺ID！');
    } else {
        isShowLoading2.value = true;

        const params = {
            external_shop_id: stepOneData.external_shop_id,
            shop_id: stepOneData.shop_id,
            retail_shop_id: routers.query.shop_id || 0
        };
        verifyNumServe(params).then((res: any) => {
            checkShopId.isCheck = true;
            checkShopId.status = res.status;
            isShowLoading2.value = false;
            checkShopId.isShow = false;
            stepOneDataRef.value.clearValidate('shop_id');
        });
    }
};

/**
 * 校验推广活动店铺ID
 */
const toverifyShopSerNumber = () => {
    // 编辑和查看时不校验店铺ID
    if (['look'].includes(routers?.query?.type)) {
        return;
    }
    if (!stepOneData.shop_ser_number) {
        ElMessage.warning('请输入店铺ID！');
    } else {
        isShowLoading3.value = true;

        const params = {
            shop_ser_number: stepOneData.shop_ser_number,
            source: 6 // 淘宝
        };
        verifyShopSerNumber(params)
            .then((res: any) => {
                checkShopSerNumber.isCheck = true;
                checkShopSerNumber.status = res?.status || 1;
                isShowLoading3.value = false;
                checkShopSerNumber.isShow = false;
                if (res) stepOneDataRef.value.clearValidate('shop_ser_number1');
            })
            .catch((err: any) => {
                err?.msg && ElMessage.error(`${err.msg}`);
                checkShopSerNumber.isCheck = false;
                checkShopSerNumber.status = 0;
                isShowLoading3.value = false;
                checkShopSerNumber.isShow = false;
                isShowLoading3.value = false;
            });
    }
};

// 下一步按钮
const nextStep = async () => {
    // 当retail_shop_id有值并且type==look时为查看，不校验必填项，不调用接口
    if (retail_shop_id && type === 'look') {
        shopInfo.shop_id = retail_shop_id;
        step.value = 2;
        return;
    }
    stepOneDataRef.value.validate(async (valid: any): Promise<void> => {
        if (valid) {
            if (
                checkCode.status == 0 &&
                stepOneData.service_application == 1 &&
                stepOneData.sync_line !== SyncLine['RPA_SYNC_LINE']
            ) {
                checkCode.isShow = true;
                stepOneDataRef.value.validateField('shop_auth_code');
                return;
            } else if (checkCode.status == 2 && stepOneData.service_application == 1) {
                checkCode.isShow = false;
                return;
            } else if (
                stepOneData.is_open_virtual == 1 &&
                checkShopId.status == 0 &&
                stepOneData.service_application == 1
            ) {
                checkShopId.isShow = true;
                stepOneDataRef.value.validateField('shop_id');
                return;
            } else if (
                stepOneData.is_open_virtual == 1 &&
                checkShopId.status > 1 &&
                stepOneData.service_application == 1
            ) {
                checkShopId.isShow = false;
                return;
            } else if (
                stepOneData.is_open_promotion == 2 &&
                checkShopSerNumber.status == 0 &&
                stepOneData.service_application == 1
            ) {
                // 当开启推广活动并且为应用服务时，校验是否校验过店铺ID
                checkShopSerNumber.isShow = true;
                stepOneDataRef.value.validateField('shop_ser_number1');
            } else if (
                stepOneData.is_open_promotion == 2 &&
                checkShopSerNumber.status != 2 &&
                stepOneData.service_application == 1
            ) {
                // 当开启推广活动并且为应用服务时
                checkShopSerNumber.isShow = false;
                return;
            } else {
                if (oldShopDetailInfo.service_application == 1 && stepOneData.service_application == 2) {
                    serviceDialogRef.value.content =
                        '您已切换为非服务应用模式，切换后，旧路线将不再提供数据同步服务，仅支持手动上传订单的模式，请谨慎操作！';
                    serviceDialogRef.value.appDialog.visible = true;
                } else {
                    onServiceDialog();
                }
            }
        }
    });
};

// 下一步最终交互逻辑，包含编辑时从应用服务切换到暂不购买二次弹窗确认回调
const onServiceDialog = async () => {
    // 当shopInfo.shop_id有值时为编辑逻辑，否则为新增

    const {
        service_application,
        sync_line,
        external_shop_id,
        shop_ser_number,
        name,
        logo,
        external_shop_index_url,
        shop_auth_code,
        is_timing_sync_order,
        order_sync_time,
        is_open_virtual,
        shop_id,
        is_open_promotion,
        promotion_type
    } = stepOneData;

    // 通用入参
    let params: any = {
        service_application,
        name,
        logo
    };

    if (service_application == 1) {
        // 应用服务入参
        params = Object.assign(params, {
            sync_line,
            external_shop_id,
            external_shop_index_url,
            shop_auth_code,
            is_timing_sync_order,
            virtual_number_serve: { is_open_virtual },
            // RPA 需求新增编辑时增加店铺ID
            shop_ser_number,
            is_open_promotion
        });
        // 当开启数据同步时需带上同步周期入参
        if (is_timing_sync_order == 1) {
            params.order_sync_time = order_sync_time;
        }
        // 当开启虚拟号服务时需带上店铺ID入参
        if (is_open_virtual == 1) {
            params.virtual_number_serve.shop_id = shop_id;
        }

        // 当开启推广活动时
        if (is_open_promotion == 2) {
            params.is_open_promotion = is_open_promotion;
            const typeArr: { id: number; name: string }[] = [];
            PROMOTION_ACTIVITY_TYPE.forEach(e => {
                promotion_type.forEach(p => {
                    if (e.id == p) {
                        typeArr.push({
                            id: e.id,
                            name: e.name
                        });
                    }
                });
            });
            params.promotion_type = typeArr;
            params.source = shopInfo.source;
        }
    } else {
        // 暂时购买入参
        params.shop_ser_number = shop_ser_number;
        // RPA 需求新增编辑时增加淘宝账号名
        params.external_shop_id = external_shop_id;
        // 推广活动
        params.is_open_promotion = 1;
        params.promotion_type = [];
    }

    if (shopInfo.shop_id) {
        // 编辑--需带上source和shop_id
        params.source = shopInfo.source;
        params.shop_id = shopInfo.shop_id;

        const { task_state, created_at, finish_time } = await editStore(params);
        stepTwoData = {
            task_state,
            created_at,
            finish_time
        };
    } else {
        // 新增--需带上source
        params.source = shopInfo.source;
        const { shop_id, open_platform } = await addStore(params);
        shopInfo.shop_id = shop_id;
        // RPA 需求 使用 retail_shop_id 展示
        shopInfo.retail_shop_id = shop_id;
        stepTwoData.open_platform = open_platform;
    }

    step.value = 2;
};

// 获取线路列表数据
const getShopList = async () => {
    const line_list = await shopLineList({ source: shopInfo.source });
    if (line_list?.length) {
        lineList.value = line_list;
    }
};

// 编辑--获取店铺信息
const getDetailInfo = async (retail_shop_id: string) => {
    const data = await getStoreDetail({ retail_shop_id });
    const {
        name,
        external_shop_id,
        external_shop_index_url,
        retail_shop_config: { order_sync_time, is_timing_sync_order, virtual_number_serve, sync_line, shop_auth_code },
        service_application,
        shop_ser_number,
        logo,
        is_open_promotion,
        promotion_type
    } = data;
    stepOneData.name = name;
    stepOneData.external_shop_id = external_shop_id;
    stepOneData.external_shop_index_url = external_shop_index_url;
    stepOneData.order_sync_time = order_sync_time || '23:00';
    stepOneData.is_timing_sync_order = is_timing_sync_order;
    stepOneData.service_application = service_application;
    stepOneData.shop_ser_number = shop_ser_number || virtual_number_serve.shop_id;
    stepOneData.is_open_virtual = virtual_number_serve.is_open_virtual;
    stepOneData.shop_id = virtual_number_serve.shop_id || shop_ser_number;
    stepOneData.sync_line = sync_line || SyncLine['DEFAULT_RPA_SYNC_LINE']; // RPA需求默认线路改为线路4
    stepOneData.shop_auth_code = shop_auth_code;
    stepOneData.logo = logo;
    stepOneData.is_open_promotion = is_open_promotion; // 是否开启推广活动
    if (promotion_type?.id) stepOneData.promotion_type = [Number(promotion_type?.id)];

    // 深拷贝记忆接口返回的初始数据
    oldShopDetailInfo = lodash.cloneDeep({
        service_application: service_application,
        is_open_virtual: virtual_number_serve.is_open_virtual
    });
};

// 修改虚拟号店铺ID时及时同步到暂不购买店铺ID
const onChangeShopId = id => {
    // 只要虚拟号店铺ID有变更需重新校验--重置校验状态
    checkShopId.isShow = false;
    checkShopId.isCheck = false;
    checkShopId.status = 0;

    stepOneData.shop_ser_number = id;
};

// 修改暂不购买店铺ID及时同步到虚拟号店铺ID
const onChangeShopSerNumber = id => {
    // 只要店铺ID有变更需重新校验--重置校验状态
    checkShopId.isShow = false;
    checkShopId.isCheck = false;
    checkShopId.status = 0;

    stepOneData.shop_id = id;
};
// 切换淘宝账号名和店铺首页和授权码重新校验
const changeValue = (val?: any) => {
    if (val == 'shop_id') {
        checkShopId.isShow = false;
        checkShopId.isCheck = false;
        checkShopId.status = 0;
    }
    checkCode.isShow = false;
    checkCode.isCheck = false;
    checkCode.status = 0;
};
// 第二步--数据初始化
const initData = e => {
    shopDateInit({ retail_shop_id: shopInfo.shop_id, task_module: 31 }).then(() => {
        parabolaAnimation(e);
        ShowTaskMessage('数据初始化异步任务创建成功');
    });
};

// 复制店铺ID
const copy = async (val: string | number) => {
    try {
        await toClipboard(val.toString());
        ElMessage.success('复制成功');
    } catch (e) {
        ElMessage.error('复制失败');
    }
};

const toSetting = () => {
    const path = '/channelconfig/developConfiguration/basicConfiguration';
    router.push(path);
};

// 跳转到隐私协议
const toAgreement = () => {
    const path = '/agreement?show=privacyAgreement';
    window.open(path, '_blank');
};

// 跳转到引导页
const toCheck = () => {
    window.open('/mao-tao-guide');
};

// 完成后跳转到店铺列表
const done = () => {
    const path = '/ecommerce/storeManage/list';
    router.push(path);
};

// 虚拟号店铺ID排版简化
const showDom = computed(() => {
    let text = '';
    if (checkShopId.status == 2) text = '该店铺还未购买服务，请先联系';
    if (checkShopId.status == 3) text = '该店铺还未授权登录，请先联系';
    if (checkShopId.status == 4) text = '该店铺已授权其他店铺，请绑定新的店铺ID';
    return text;
});

// 计算内容区域初始化高度
const height = computed(() => {
    const clientHeight = document.documentElement.clientHeight;
    return `${clientHeight - 364}px`;
});

// 禁用逻辑
const isDisabledDom = computed(() => {
    return (
        oldShopDetailInfo.service_application == 2 ||
        (oldShopDetailInfo.service_application == 1 && oldShopDetailInfo.is_open_virtual == 1)
    );
});

// 初始化数据展示逻辑
const initBut = computed(() => (type: number) => {
    return stepOneData.service_application == 1 && stepOneData.is_open_virtual == 1 && stepTwoData.task_state == type;
});

//清空上传图片组件的校验
watch(
    () => stepOneData.logo,
    val => {
        stepOneDataRef.value.clearValidate('logo');
    }
);

//淘宝账号禁用逻辑
const exterDom = computed(() => {
    return (routers.query.shop_id && oldShopDetailInfo.service_application == 1) || type == 'edit';
});

//页面类型，默认编辑
const pageType = ref('');
onMounted(async () => {
    shopInfo.source = Number(routers.query.source);

    await getShopList();

    if (routers.query?.shop_id) {
        shopInfo.shop_id = routers.query.shop_id;
        // 使用列表 retail_shop_id 做下一步完成时展示用
        shopInfo.retail_shop_id = routers.query.retail_shop_id;

        await getDetailInfo(shopInfo.shop_id as string);
    }
    if (routers.query?.type) pageType.value = routers.query?.type as string;
});
</script>

<style scoped lang="scss">
.content {
    display: flex;
    justify-content: space-between;
    height: calc(100vh - 339px);

    .withTips {
        display: flex;
        align-items: center;

        .el-input {
            width: 400px;
        }
    }

    .formTips {
        line-height: 1.6;
        font-size: 12px;
        color: #999;
        background-color: #fffaf9;
        padding: 8px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;

        .toAgreement {
            color: #ff6b00;

            &:hover {
                cursor: pointer;
                color: #f99547;
            }
        }

        .tips_title {
            font-size: 14px;
            color: #ff6b00;
            font-weight: 600;
            margin-bottom: 2px;
        }
    }

    .syncTime {
        display: flex;
        align-items: center;

        span {
            // font-size: 13px;
            color: #777;
            white-space: nowrap;
        }

        .margin-l {
            margin-right: 6px;
        }

        .margin-r {
            margin-left: 6px;
        }

        :deep .el-input {
            width: 160px;
        }
    }

    .storeTips {
        flex: 1;
    }

    .line {
        width: 0;
        border-left: 1px dashed #eee;
        margin: 0 20px 0 8px;
    }

    .msg {
        flex: 1;
        height: v-bind(height);
        overflow: auto;
        padding-left: 10px;
        padding-right: 36px;
        box-sizing: border-box;

        .title {
            border-left: 3px solid #ff6b00;
            padding-left: 8px;
            margin: 10px 0 24px;
        }

        .auth-step {
            margin-bottom: 20px;

            .step-header {
                display: flex;
                justify-content: space-between;
                align-items: center;

                span {
                    font-size: 13px;
                    font-weight: 500;
                    color: #555;
                }
            }

            .step-tips {
                display: flex;
                align-items: center;
                margin: 12px 0;
                padding-left: 16px;

                .tips-dot {
                    width: 8px;
                    height: 8px;
                    border-radius: 50%;
                    background-color: #ff6b00;
                }

                .tips-text {
                    text-indent: 6px;
                    font-size: 13px;
                    font-weight: 300;
                    color: #555;
                    line-height: 1.5;
                }
            }

            .step-img {
                width: 100%;
                background-color: #fcfcfc;

                img {
                    width: 100%;
                }
            }
        }
    }

    .finishBox {
        flex: 1;
        height: 500px;
        padding-left: 30px;
        padding-bottom: 100px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        & > div {
            line-height: 1;
            font-size: 13px;
            color: #555;
            margin-top: 16px;
        }

        .tag {
            margin-top: 10px;

            span {
                color: #ff6b00;

                &:hover {
                    cursor: pointer;
                }
            }
        }
    }
}

.next {
    display: flex;
    justify-content: flex-end;
}

.finished {
    display: flex;
    justify-content: flex-end;
}

.customerTips {
    margin-left: 10px;
    line-height: 1.4;
    font-size: 12px;
    color: #999;
}

.customer-sever {
    margin-left: 25px;
}

.customerService {
    cursor: pointer;
    color: #ff6b00;
}

.virtualNumber {
    background-color: #f5f5f5;
    padding: 10px 0 20px;
}

.verify-btn {
    font-size: 12px;
    color: #f76c6c;
    cursor: pointer;
}

.verify-fail-text {
    font-size: 12px;
    color: #f76c6c;

    .customer {
        cursor: pointer;
        color: #1890ff;
    }
}

.verify-pass-text {
    font-size: 12px;
    color: #00e266;
}

.init-data {
    text-align: center;

    .time-color {
        color: #ff6b00;
        margin-top: 10px;
    }

    .time-warning {
        color: #f76c6c;
        margin-top: 10px;
    }

    .time-tips {
        margin-top: 10px;
    }
}

.rotate-loading {
    animation: rotating 2s linear infinite reverse;
}

.tip-url {
    white-space: nowrap;
    text-indent: 12px;
    font-size: 12px;
    color: #ff6b00;

    &:hover {
        color: #f99547;
        cursor: pointer;
    }
}

.link-indent {
    text-indent: 0;
}

.footer_button {
    text-align: center;
    background-color: #fff;
    padding: 16px 24px;
    margin: 0 -16px -16px;
    border-top: 1px solid #eaeaea;
}
</style>
